package com.jiubaisoft.myrefresh;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;


import com.songdehuai.widget.myrefreshlayout.RefreshListenerAdapter;
import com.songdehuai.widget.myrefreshlayout.MyRefreshLayout;
import com.songdehuai.myrefresh.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    ListView mainLv;
    MyRefreshLayout refreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
    }

    MainListAdapter mainListAdapter;

    private void initViews() {
        refreshLayout = (MyRefreshLayout) findViewById(R.id.refreshLayout);
        mainLv = (ListView) findViewById(R.id.mainLv);
        mainListAdapter = new MainListAdapter(getApplicationContext(), listDatas);
        mainLv.setAdapter(mainListAdapter);
        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(MyRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                getListDatas(false);
            }

            @Override
            public void onLoadMore(MyRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                getListDatas(true);
            }
        });
        refreshLayout.startRefresh();
        mainLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(MainActivity.this, "点击", Toast.LENGTH_SHORT).show();
            }
        });
    }


    List<String> listDatas = new ArrayList<>();
    int count = 0;

    void getListDatas(boolean isMore) {
        if (!isMore) {
            listDatas.clear();
            count = 0;
        }
        for (int i = 0; i < 10; i++) {
            listDatas.add("测试数据" + count);
            count++;
        }
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                mainLv.post(new Runnable() {
                    @Override
                    public void run() {
                        mainListAdapter.notifyDataSetChanged();
                        refreshLayout.finish();
                    }
                });
            }
        }, 1000);
    }
}
